package com.zr.sms.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zr.sms.model.Employee;
import com.zr.sms.service.AddService;
import com.zr.sms.service.UpdateService;
import com.zr.sms.serviceimpl.AddServiceImpl;
import com.zr.sms.serviceimpl.UpdateServiceImpl;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
/**
 * 提交购物订单
 * @author wangbs
 *
 */
public class SubmitorderServlet extends HttpServlet {
	AddService add=new AddServiceImpl();
	UpdateService up=new UpdateServiceImpl();
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
	  		throws ServletException, IOException {
	  req.setCharacterEncoding("utf-8");
	  resp.setCharacterEncoding("utf-8");
	  String goods=req.getParameter("goods");
	  JSONObject obj=JSONObject.fromObject(goods);
	  
	  
	  String moneystring=obj.getString("gmoneys");
	
	  String []ms=moneystring.split(",");
	  
	  String gidstring=obj.getString("gids");
	 
	  String []gs=gidstring.split(",");//获取商品id的字符串素组
	  
	  String numtring=obj.getString("gnumbers");
	
	  String []ns=numtring.split(",");//获取购买商品的件数的字符串素组
	  for (int i = 0; i < ns.length; i++) {
		up.updataGoods(Integer.parseInt(gs[i]),Integer.parseInt(ns[i]));
   	}
	  
	  double totalmoney=0;
	  for (int i = 0; i < ms.length; i++) {
		totalmoney=totalmoney+Double.parseDouble(ms[i]);//获取清单总金额
	  }
	  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	  Date date=new Date();
	  String dateStr=sdf.format(date);//获取当前时间
	  
	  
	  Employee emp=(Employee) req.getSession().getAttribute("currentemp");
	  int eid=emp.getEid();//获取当前收银员id
	  int cid=emp.getCid();
	  up.addMoney(totalmoney, cid);
	  
      boolean flag= add.addShopList(dateStr, obj.toString(), totalmoney, eid);
      PrintWriter out=resp.getWriter();
      JSONObject json=new JSONObject();
      json.put("msg", "清单生成成功");
      json.put("total", String.valueOf(totalmoney));
      if(flag==true){
    	  out.write(json.toString());
      }
      
	  
	  
	 
	  
	  
	  
	  
	  
       
	}

}
